package com.adwin.addcoin.repository.Repost

import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.adwin.addcoin.repository.api.TestApi
import com.adwin.addcoin.repository.net.RetrofitClient
import com.adwin.addcoin.utils.dataStore
import com.adwin.addcoin.utils.getAgreement
import com.adwin.addcoin.utils.getRePost
import com.adwin.addcoin.utils.getRepostNumber
import com.adwin.addcoin.utils.log
import com.adwin.addcoin.utils.saveRepostNumber
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONArray
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger


object BurialSiteRepostUtils {

    private var netNumber = AtomicInteger(0)
    private var isNetWork = AtomicBoolean(false)

    fun repostStart(mContext:Context){
        GlobalScope.launch(Dispatchers.IO) {
            if (!isNetWork.get()&& netNumber.get() > 15){
                var repostCode = mContext.getRepostNumber()
                val post =  mContext.getRePost()
                if (post.length()>0){
                    sendToRepost(post.toString(),post,repostCode,mContext)
                }
            }else if(!isNetWork.get()){
                netNumber.set(netNumber.get()+1)
            }
        }
    }

    /**
     * 埋点上报  [{"account_id":"088f3aaa-5641-4403-ac37-724198dfceda","app_id":"da81795be0a64aab9c8c4d5aca63bbb4","app_version":"1.0","brand":"google","bundle_id":"com.adwin.addcoin","event_name":"adcoin_Google_Login_error","imei":"","log_id":"73e8c8bd-1fde-4ca1-8a22-d1bab6d9f6a2","manufacturer":"Google","os":"android","os_version":"13","simulator":false,"system_language":"en","time":"2023-05-31 14:28:11.365","type":"track","zone_offset":8}]
     */
    private fun sendToRepost(jsonSting:String,json:JSONArray,number:Int,mContext: Context){
        GlobalScope.launch(Dispatchers.IO) {
            isNetWork.set(true)
            val requestBody: RequestBody = MultipartBody.create(MediaType.get("application/json;charset=utf-8"), json.toString())
            RetrofitClient.getInstance().getService(TestApi::class.java).syncData(requestBody)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                    if (!TextUtils.isEmpty(it)){
                        GlobalScope.launch (Dispatchers.IO){
                            mContext.dataStore.saveRepostNumber(number+json.length())
                            "sendToRepost:${json.toString()}   title:$it".log()
                            netNumber.set(0)
                            isNetWork.set(false)
                        }
                    }else{
                        isNetWork.set(false)
                    }
                },{
                    isNetWork.set(false)
                    Log.d("checkIn","checkIn   no ${it.message}")
                })
        }

    }

    /**
     * app是否处于后台
     */
    fun isBackground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appProcesses = activityManager.runningAppProcesses
        val var3: Iterator<*> = appProcesses.iterator()
        var appProcess: RunningAppProcessInfo
        do {
            if (!var3.hasNext()) {
                return false
            }
            appProcess = var3.next() as RunningAppProcessInfo
        } while (appProcess.processName != context.packageName)
        return appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND
    }




}